package com.baidu.bridge.conf.Retrofit;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.Header;
import com.baidu.bridge.api.AbApiService;
import com.baidu.bridge.conf.BridgeConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import java.util.concurrent.TimeUnit;

@Configuration
@RequiredArgsConstructor
@Slf4j
public class AbRetrofitConfig {

    private final BridgeConfig bridgeConfig;

    // 配置 OkHttp 客户端（可根据需要添加拦截器、超时时间等）
    @Bean("abOkHttpClient")
    public OkHttpClient okHttpClient() {
        // 创建日志拦截器
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // 打印完整请求体和响应体

        return new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .addInterceptor(chain -> {
                    Request originalRequest = chain.request();
                    String token = bridgeConfig.getAb().getToken();
                    Request newRequest = originalRequest.newBuilder()
                            .header(Header.AUTHORIZATION.getValue(), StrUtil.format("Bearer {}", token))
                            .header(StrUtil.format("X-{}", Header.AUTHORIZATION.getValue()), StrUtil.format("Bearer {}", token))
                            .build();
                    return chain.proceed(newRequest);
                })
                .addInterceptor(loggingInterceptor) // 添加日志拦截器
                .build();
    }

    // 配置 Retrofit 实例（替换为你的接口域名）
    @Bean("abRetrofit")
    public Retrofit retrofit(@Qualifier("abOkHttpClient") OkHttpClient okHttpClient) {
        return new Retrofit.Builder()
                .baseUrl(bridgeConfig.getAb().getUrl())
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    // 注入 ApiService
    @Bean
    public AbApiService abApiService(@Qualifier("abRetrofit") Retrofit retrofit) {
        log.info("初始化 ab系统 api 服务 : url:{}",bridgeConfig.getAb().getUrl());
        return retrofit.create(AbApiService.class);
    }
}